package com.zidian.study.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zidian.student.trucks.R;
import com.zidian.study.adapter.ActionDetailAdapter;
import com.zidian.study.bean.ActionDetailBean;
import com.zidian.study.event.AttendActionEvent;
import com.zidian.study.globa.Constant;
import com.zidian.study.globa.ToolBarActivity;
import com.zidian.study.utils.GetUserInfo;
import com.zidian.study.utils.ToastUtil;
import com.zidian.study.view.GlideImageLoader;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2016/9/2 0002.
 * 活动详情界面
 */
public class TaskActionDetailActivity extends ToolBarActivity {
    @Bind(R.id.detail_title)
    TextView detailTitle;
    @Bind(R.id.detail_time)
    TextView detailTime;
    @Bind(R.id.detail_pub)
    TextView detailPub;
    @Bind(R.id.detail_content)
    TextView detailContent;
    @Bind(R.id.act_detail_image)
    ImageView actDetailImage;
    @Bind(R.id.detail_place)
    TextView actionPlaceTv;
    @Bind(R.id.detail_number)
    TextView actionNumberTv;
    @Bind(R.id.action_people_tv)
    TextView actionPeopleTv;
    @Bind(R.id.act_banner)
    Banner actBanner;

    private List<String> data = new ArrayList<>();
    private ActionDetailAdapter adapter = new ActionDetailAdapter(this, data);
    private Handler handler = new Handler();
    private String activityId;
    private String imageUrl;
    private int functionAttendance;
    private int functionAttendanceSum;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setToolbarView(R.layout.toolbar_left);
        setContentView(R.layout.activity_action_detail);
        ButterKnife.bind(this);
        setTitle("活动详情");
        activityId = getIntent().getStringExtra("activityId");
        imageUrl = getIntent().getStringExtra("imageUrl");
        functionAttendance = getIntent().getIntExtra("functionAttendance",0);
        functionAttendanceSum = getIntent().getIntExtra("functionAttendanceSum",0);
        initView();
        initData();
        getActionDetail();
    }

    public void initView() {
        Glide.with(this)
                .load(imageUrl)
                .placeholder(R.mipmap.case_news_bg_93)
                .centerCrop()
                .into(actDetailImage);
        actionPeopleTv.setText("人数" + functionAttendance + "/" + functionAttendanceSum);
        actBanner.setImageLoader(new GlideImageLoader());
        actBanner.setIndicatorGravity(BannerConfig.RIGHT);
        actBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);

    }


    public void initData() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        }, 1500);

    }

    /**
     * 获取测试数据
     */
    private void getData() {
        adapter.notifyDataSetChanged();
        adapter.notifyItemRemoved(adapter.getItemCount());
    }

    private void getActionDetail() {

        String url = Constant.URL_GOAL + "activity/selectOne";

        Map<String, String> map = new HashMap<>();
        map.put("activityId", activityId);
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));


        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("T", e.toString());
            }

            @Override
            public void onResponse(String response, int id) {

                Log.e("T", response);

                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(response);
                    int resultCode = jsonObject.getInt("code");

                    if (resultCode != 200) {

                        if (resultCode == 201) {
                            return;
                        }

                        return;
                    }

                } catch (JSONException e) {


                }

                Gson gson = new Gson();
                ActionDetailBean actionBean = gson.fromJson(response, ActionDetailBean.class);
                if (actionBean.isSuccess()) {
                    detailContent.setText(actionBean.getData().getActivityContent().getContent());
                    detailTime.setText("活动时间： " + actionBean.getData().getActivityTime());
                    detailTitle.setText(actionBean.getData().getActivityCollege());
                    detailPub.setText("发布者:"+actionBean.getData().getActivityCollege());
                    actionPlaceTv.setText( "活动地点： " + actionBean.getData().getActivityLocation());
                    actionNumberTv.setText("联系电话:" + actionBean.getData().getActivityCollegeNumber());
//                    data.addAll(actionBean.getData().getActivityContent().getUrl());
                    List<String> images = new ArrayList<String>();
                    for (int i = 0; i < actionBean.getData().getActivityContent().getUrl().size(); i++) {
                        images.add(actionBean.getData().getActivityContent().getUrl().get(i).getActivityPictureUrl());
                    }
                    actBanner.setImages(images);
                    actBanner.start();
                }

            }
        });
    }

    /**
     * 查看活动参加人
     */
    @OnClick(R.id.action_people_tv)
    public void onActionPeopleClick() {
        Intent intent = new Intent(context,ActionPeopleActivity.class);
        intent.putExtra("activityId",activityId);
        intent.putExtra("count",functionAttendance + "/" + functionAttendanceSum);
        startActivity(intent);
    }

    @OnClick(R.id.action_attend_bt)
    public void onAttendActionClick(){
        attendAction();
    }
    private void attendAction(){
        String url = Constant.URL_GOAL + "activity/joinNum";
        Map<String, String> map = new HashMap<>();
        map.put("activityId", activityId);
        map.put("studentId", GetUserInfo.getStudentId(context));
        map.put("token", GetUserInfo.getToken(context));

        OkHttpUtils.post().url(url).params(map).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Snackbar.make(actionNumberTv,"报名失败",Snackbar.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject= new JSONObject(response);
                    int code = jsonObject.getInt("code");
                    if (code == 200) {
                        //发送事件
                        EventBus.getDefault().post(new AttendActionEvent(true));
                        ToastUtil.showToast(context,"参加成功");
                        finish();
                    }
                    else {
                        Snackbar.make(actionNumberTv,jsonObject.getString("message"),Snackbar.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

}
